package filter

import (
	"easyblog/utils/errmsg"
	"easyblog/utils/jwt"
	"github.com/beego/beego/v2/server/web/context"
	"strings"
	"time"
)

//用户是否登录判断的过滤函数
var LoginFilter = func(ctx *context.Context) {
	tokenHeader := ctx.Request.Header.Get("Authorization")
	//fmt.Println(tokenHeader)

	if ctx.Request.RequestURI != "/admin/login" {

		//token不存在
		if tokenHeader == "" {
			code := errmsg.ERROR_TOKEN_NOT_EXIST //token不存在
			ctx.RenderMethodResult(map[string]interface{}{
				"status":  code,
				"message": errmsg.GetErrmsg(code),
			})
			ctx.Redirect(302, "/login")
			return
		}

		//token字符串格式错误
		checkToken := strings.SplitN(tokenHeader, " ", 2)
		if len(checkToken) != 2 && checkToken[0] != "Bearer" {
			code := errmsg.ERROR_TOKEN_TYPE_WRONG //token字符串格式错误
			ctx.RenderMethodResult(map[string]interface{}{
				"status":  code,
				"message": errmsg.GetErrmsg(code),
			})
			return
		}

		//token验证失败
		key, tCode := jwt.ParseToken(checkToken[1])
		if tCode == errmsg.ERROR {
			code := errmsg.ERROR_TOKEN_WRONG //token验证失败
			ctx.RenderMethodResult(map[string]interface{}{
				"status":  code,
				"message": errmsg.GetErrmsg(code),
			})
			return
		}

		// token过期
		if time.Now().Unix() > key.ExpiresAt.Unix() {
			code := errmsg.ERROR_TOKEN_RUNTIME
			ctx.RenderMethodResult(map[string]interface{}{
				"status":  code,
				"message": errmsg.GetErrmsg(code),
			})
			ctx.Redirect(302, "/login")
			return
		}
	}
}